﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
using FORM = System.Windows.Forms;
using System.IO;
using System.Reflection;

namespace intelliEssayHelpAgent
{
    /// <summary>
    /// See Method 'QParagraphCenterStatus' in intelliEssay Development Assistant
    /// </summary>
    public partial class MainWindow : Window
    {
        string defaultDirectoryPath = "";
        Slider resolutionChanger = new Slider();
        TextBox defaultDirectory = new TextBox() { Height = 20, MinWidth = 50, Margin = new Thickness(10) };
        TextBox searchBox = new TextBox() { Height = 20, MinWidth = 50, Margin = new Thickness(10) };
        ListBox intelliSenseList = new ListBox() { SelectionMode = SelectionMode.Single, MinHeight = 0, MinWidth = 100 };
        Button submitDefaultDirectoryChange = new Button() { Content = "Set", Height = 20, Width = 30 };
        StackPanel smartJumpPanel = new StackPanel() { Orientation = System.Windows.Controls.Orientation.Vertical };
        StackPanel searchPanel = new StackPanel() { Orientation = Orientation.Vertical };
        StackPanel directorySetting = new StackPanel() { Orientation = System.Windows.Controls.Orientation.Vertical };
        StackPanel resolutionChangerHelper = new StackPanel() { Orientation = Orientation.Vertical };
        StackPanel stkpnl = new StackPanel() { Orientation = Orientation.Horizontal };
        TextBlock resolutionCurrent = new TextBlock() { Text = "...", Foreground = Brushes.White, Height = 75 };
        TextBlock maximizeWindow = new TextBlock() { Text = "Maximize", Foreground = Brushes.White, Height = 55 };
        TextBlock minimizeWindow = new TextBlock() { Text = "Tools Only", Foreground = Brushes.White };
        FileSystemWatcher fileSysWatcher;
        string lastAffectedPath;
        string[] SmartJumpTag = new string[5];
        string[] SmartJumpDestination = new string[5];
        public MainWindow()
        {
            InitializeComponent();
            this.MouseLeftButtonDown += new MouseButtonEventHandler(MainWindow_MouseLeftButtonDown);
            resolutionChanger.Orientation = Orientation.Vertical;
            resolutionChanger.Maximum = 5;
            resolutionChanger.Minimum = 0;
            resolutionChanger.Height = 150;
            resolutionChanger.Width = 40;
            resolutionChanger.Value = 1;
            resolutionChanger.ValueChanged += new RoutedPropertyChangedEventHandler<double>(resolutionChanger_ValueChanged);
            resolutionChanger.PreviewMouseWheel += new MouseWheelEventHandler(resolutionChanger_MouseWheel);
            resolutionChangerHelper.Children.Add(maximizeWindow);
            resolutionChangerHelper.Children.Add(resolutionCurrent);
            resolutionChangerHelper.Children.Add(minimizeWindow);
            stkpnl.Children.Add(resolutionChanger);
            stkpnl.Children.Add(resolutionChangerHelper);
            directorySetting.Children.Add(defaultDirectory);
            directorySetting.Children.Add(submitDefaultDirectoryChange);
            submitDefaultDirectoryChange.Click += new RoutedEventHandler(submitDefaultDirectoryChange_Click);
            searchPanel.Children.Add(searchBox);
            searchPanel.Children.Add(intelliSenseList);
            searchBox.TextChanged += new TextChangedEventHandler(searchBox_TextChanged);
            intelliSenseList.PreviewMouseDoubleClick += new MouseButtonEventHandler(intelliSenseList_MouseLeftButtonDown);
            try
            {
                fileSysWatcher = new FileSystemWatcher("x:\\");
                fileSysWatcher.EnableRaisingEvents = true;
                fileSysWatcher.IncludeSubdirectories = true;
                fileSysWatcher.Created += fileSysWatcher_Created;
                Topmost = true;
                MainBorder.Visibility = Visibility.Collapsed;
                resolutionCurrent.Text = "Hidden";
                this.ShowInTaskbar = false;

                System.IO.StreamReader sr = new StreamReader(File.Open("smartjumpinfo.txt", FileMode.Open));
                for (int i = 0; i < 5; i++)
                {
                    smartJumpPanel.Children.Add(new Button() { Content = sr.ReadLine() });

                }
            }
            catch
            {
                for (int i = 0; i < 5; i++)
                {
                    smartJumpPanel.Children.Add(new Button() { Content = "SmartJump has no idea where are you going" });
                }
            }
        }

        void fileSysWatcher_Created(object sender, FileSystemEventArgs e)
        {
            if (!e.FullPath.ToLower().Contains("intelliessay."))
            {
                return;
            }
            if (!e.FullPath.ToLowerInvariant().EndsWith(".dll"))
            {
                return;
            }
            int verIdx = e.FullPath.LastIndexOf('\\');
            int verIdx2 = e.FullPath.LastIndexOf("\\", verIdx - 1);
            StringBuilder sb = new StringBuilder();
            sb.Append("An intelliEssay Component has been released, please make changes to your code if necessary\n");
            sb.Append("Conponent Name:" + e.FullPath.Substring(verIdx + 1, e.FullPath.Length - verIdx - 1) + "\n");
            sb.Append("Version:" + e.FullPath.Substring(verIdx2 + 1, verIdx - verIdx2 - 1));
            this.Dispatcher.Invoke(new Action(() =>
                {
                    MailNotification mn = new MailNotification(true);
                    mn.MailMessage.AcceptsReturn = true;
                    mn.MailMessage.Text = sb.ToString();
                    mn.Topmost = true;
                    mn.Show();
                }));
        }




        void searchBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            string text = searchBox.Text;
            try
            {
                intelliSenseList.ItemsSource = HelpAndSupportItemCollection.GetCurrentHelpCollection()[text];
            }
            catch
            {
            }
        }

        void Browser_Loaded(object sender, RoutedEventArgs e)
        {
            //    ((Storyboard)Resources["ShowContent"]).Begin();
        }

        void Browser_SourceUpdated(object sender, DataTransferEventArgs e)
        {
            //   ((Storyboard)Resources["LoadContent"]).Begin();
        }

        void intelliSenseList_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                HelpAndSupportItem hasi = (HelpAndSupportItem)intelliSenseList.SelectedItem;
                FlowDocument fd = Browser.Document;
                TextRange txtrng = new TextRange(fd.ContentStart, fd.ContentEnd);
                System.IO.Stream STR = new System.IO.FileStream(hasi.URI, System.IO.FileMode.Open);
                txtrng.Load(STR, System.Windows.DataFormats.Rtf);
            }
            catch
            {
            }
        }
        int smartTagIndex = 0;
        void submitDefaultDirectoryChange_Click(object sender, RoutedEventArgs e)
        {

            fileSysWatcher.EnableRaisingEvents = false;
            string filePath = defaultDirectory.Text;
            FileInfo thisFile = new FileInfo(filePath);
            Button b = smartJumpPanel.Children[smartTagIndex++ % 5] as Button;
            b.Content = thisFile.Directory.FullName;
            Assembly ass = Assembly.LoadFrom(filePath);
            string assemblyName = ass.FullName.Split(',')[0];
            string directoryName = "intelliEssay" + "." + assemblyName.Substring(12, assemblyName.Length - 12);
            string version = ass.FullName.Split(',')[1];
            version = version.Substring(9, version.Length - 9);

            if (!Directory.Exists("x:\\" + directoryName))
            {
                Directory.CreateDirectory("x:\\" + directoryName + "\\" + version);
                Directory.CreateDirectory("x:\\" + directoryName + "\\Latest Release");
                File.Move(filePath, "x:\\" + directoryName + "\\" + version + "\\" + assemblyName + thisFile.Extension);
                File.Move(filePath, "x:\\" + directoryName + "\\Latest Release\\" + assemblyName + thisFile.Extension);
            }
            else
            {
                IEnumerable<string> versions = Directory.GetDirectories("x:\\" + directoryName);
                string highestVersion = versions.Where<string>(o => !o.Contains("Latest Release") && o.CompareTo("x:\\" + directoryName + "\\" + version) < 0).Max();
                if (!Directory.Exists("x:\\" + directoryName + "\\" + version))
                {
                    Directory.CreateDirectory("x:\\" + directoryName + "\\" + version);
                }
                if (!Directory.Exists("x:\\" + directoryName + "\\Latest Release"))
                {
                    Directory.CreateDirectory("x:\\" + directoryName + "\\Latest Release");
                }

                if (File.Exists("x:\\" + directoryName + "\\" + version + "\\" + assemblyName + thisFile.Extension))
                {
                    File.Delete("x:\\" + directoryName + "\\" + version + "\\" + assemblyName + thisFile.Extension);
                }
                File.Move(filePath, "x:\\" + directoryName + "\\" + version + "\\" + assemblyName + thisFile.Extension);
                if (File.Exists("x:\\" + directoryName + "\\Latest Release\\" + assemblyName + thisFile.Extension))
                {
                    File.Delete("x:\\" + directoryName + "\\Latest Release\\" + assemblyName + thisFile.Extension);
                }
                File.Move(filePath, "x:\\" + directoryName + "\\Latest Release\\" + assemblyName + thisFile.Extension);
                if (highestVersion != null)
                {
                    IEnumerable<string> files = Directory.GetFiles(highestVersion).Where<string>(o => !o.Contains(assemblyName + thisFile.Extension));
                    foreach (string file in files)
                    {
                        FileInfo fi = new FileInfo(file);
                        try
                        {
                            if (File.Exists("x:\\intelliEssay." + fi.Name.Substring(12, fi.Name.Length - 12 - fi.Extension.Length) + "\\Latest Release\\" + fi.Name))
                            {
                                FileInfo fiNew = new FileInfo("x:\\intelliEssay." + fi.Name.Substring(12, fi.Name.Length - 12 - fi.Extension.Length) + "\\Latest Release\\" + fi.Name);
                                if (File.Exists("x:\\" + directoryName + "\\Latest Release\\" + fi.Name))
                                {
                                    File.Delete("x:\\" + directoryName + "\\Latest Release\\" + fi.Name);
                                }
                                if (File.Exists("x:\\" + directoryName + "\\" + version + "\\" + fi.Name))
                                {
                                    File.Delete("x:\\" + directoryName + "\\" + version + "\\" + fi.Name);
                                }
                                fiNew.CopyTo("x:\\" + directoryName + "\\Latest Release\\" + fi.Name);
                                fiNew.CopyTo("x:\\" + directoryName + "\\" + version + "\\" + fi.Name);
                            }
                            else
                            {
                                if (!File.Exists("x:\\" + directoryName + "\\Latest Release\\" + fi.Name))
                                    fi.CopyTo("x:\\" + directoryName + "\\Latest Release\\" + fi.Name);
                                fi.CopyTo("x:\\" + directoryName + "\\" + version + "\\" + fi.Name);
                            }
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }
            }
            string developerId = intelliEssay.ApplicationExceptionReportingRecordingRedistributing.DeveloperInformation.GetUserNameFromAllHints();
            var pairs = intelliEssay.ApplicationExceptionReportingRecordingRedistributing.DeveloperInformation.GetAllDeveloperAssemblyPair().ToList();
            var testPair = from pair in pairs where pair.assemblyName.ToLowerInvariant() == assemblyName.ToLowerInvariant() select pair;
            if (testPair.Count() == 0)
            {
                pairs.Add(new intelliEssay.ApplicationExceptionReportingRecordingRedistributing.Assembly_Author_Pair() { assemblyName = assemblyName, authorName = developerId });
            }
            intelliEssay.ApplicationExceptionReportingRecordingRedistributing.DeveloperInformation.SaveDeveloperAssemblyPair(pairs.ToArray());
            StringBuilder sb = new StringBuilder();
            sb.Append("An intelliEssay Component has been released, please make changes to your code if necessary\n");
            sb.Append("Conponent Name:" + assemblyName + "\n");
            sb.Append("Version:" + version);
            this.Dispatcher.Invoke(new Action(() =>
            {
                MailNotification mn = new MailNotification(true);
                mn.MailMessage.AcceptsReturn = true;
                mn.MailMessage.Text = sb.ToString();
                mn.Topmost = true;
                mn.Show();
            }));
            fileSysWatcher.EnableRaisingEvents = true;
        }

        void resolutionChanger_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (e.Delta > 0)
                resolutionChanger.Value++;
            else
                resolutionChanger.Value--;
        }

        void resolutionChanger_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            AdjustSize(e.NewValue);
        }

        private void AdjustSize(double e)
        {
            if (e == 5)
            {
                WindowState = WindowState.Maximized;
                resolutionCurrent.Text = "Maximized";
                return;
            }
            if (e == 0)
            {
                Topmost = true;
                MainBorder.Visibility = Visibility.Collapsed;
                resolutionCurrent.Text = "Hidden";
                this.ShowInTaskbar = false;
                return;
            }
            double NewVal = e < 1 ? 1 : e;
            MainBorder.Visibility = Visibility.Visible;
            this.ShowInTaskbar = true;
            WindowState = WindowState.Normal;
            Topmost = false;
            this.Height = NewVal * 415;
            this.Width = NewVal * 650;
            resolutionCurrent.Text = Height + "x" + Width;
        }

        void MainWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            PopUpMenu.IsOpen = false;
            this.DragMove();
        }

        private void MouseEnterToolItem(object sender, MouseEventArgs e)
        {
            ((Storyboard)Resources["OnMouseEnter1"]).Begin((FrameworkElement)sender);
        }

        private void MouseLeaveToolItem(object sender, MouseEventArgs e)
        {
            ((Storyboard)Resources["OnMouseLeave1"]).Begin((FrameworkElement)sender);
        }

        private void MouseLeftButtonDownToolItem(object sender, MouseButtonEventArgs e)
        {
            PopUpGrid.Children.Clear();
            if (sender == ResolutionSwitch)
            {
                resolutionCurrent.Text = this.RenderSize.Height + " x " + this.RenderSize.Width;
                resolutionChanger.Focus();
                PopUpMenu.HorizontalOffset = 10;
                PopUpGrid.Children.Add(stkpnl);
            }
            if (sender == intelliEssayBugCheck)
            {
                try
                {
                    System.Diagnostics.Process.Start(@"X:\intelliEssayBugCheck\Bug Check System\intelliessaybugchecksystem.exe");
                }
                catch
                {
                }
            }
            if (sender == Publish)
            {
                MailNotification mn = new MailNotification(true);
                mn.ShowDialog();
            }
            if (sender == SearchTool)
            {
                PopUpMenu.HorizontalOffset = 160;
                PopUpGrid.Children.Add(searchPanel);
            }
            if (sender == ToolSwitch)
            {
                PopUpMenu.HorizontalOffset = 210;
                if (SearchTool.Visibility != Visibility.Visible)
                {
                    ((Storyboard)Resources["ShowToolBar"]).Begin();
                }
                else
                {
                    ((Storyboard)Resources["HideToolBar"]).Begin();
                }
            }
            if (sender == RegisterDllButton)
            {
                defaultDirectory.Text = "使用拖拽或在这里输入路径";
                PopUpMenu.HorizontalOffset = 200;
                PopUpGrid.Children.Add(directorySetting);
            }
            if (sender == Documentation)
            {
                try
                {
                    System.Diagnostics.Process.Start("x:\\intelliEssay Documentation.chm");
                }
                catch
                {
                }
            }
            if (sender == WhatsNew)
            {
                MessageBox.Show("You need first to Establish Microsoft® Visual Studio Team Foundation Server® to enable this feature.\nHowever, this is not available yet.");
            }
            if (sender == SmartJump)
            {
                PopUpMenu.HorizontalOffset = 300;
                PopUpGrid.Children.Add(smartJumpPanel);
                int idx = 0;
                foreach (Button butt in smartJumpPanel.Children.Cast<Button>())
                {
                    butt.Click += new RoutedEventHandler(butt_Click);
                }
            }
            PopUpMenu.IsOpen = true;
            e.Handled = true;
        }
        void butt_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start((sender as Button).Content.ToString());
            }
            catch
            { }

        }

        private void Grid_DragEnter(object sender, DragEventArgs e)
        {
            string[] Data = (string[])e.Data.GetData(DataFormats.FileDrop);
            foreach (string Path in Data)
            {
                defaultDirectory.Text = Path;
                submitDefaultDirectoryChange_Click(null, null);
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            StreamWriter sw = new System.IO.StreamWriter(File.Open("SmartJumpInfo.txt", FileMode.OpenOrCreate));
            for (int i = 0; i < 5; i++)
            {
                sw.WriteLine((smartJumpPanel.Children[i] as Button).Content.ToString());
            }
            sw.Close();
        }

    }
}
